package com.quartet.modules.vehicle.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.quartet.api.PageResult;
import com.quartet.api.PageResultMap;
import com.quartet.modules.customer.dao.TCustomerInfoDao;
import com.quartet.modules.home.dto.TTerminalCurrentPositionResponseDto;
import com.quartet.modules.home.dto.TerminalOnLineStatusResponseDto;
import com.quartet.modules.order.service.TOrderService;
import com.quartet.modules.platform.dto.*;
import com.quartet.modules.stock.dao.TTerminalStockDao;
import com.quartet.modules.vehicle.dao.TTerminalPositionInfoDao;
import com.quartet.modules.vehicle.dao.TVehicleInfoDao;
import com.quartet.modules.vehicle.dto.*;
import com.quartet.modules.vehicle.entity.TTerminalPositionInfo;
import com.quartet.modules.vehicle.service.TTerminalPositionInfoService;
import com.quartet.utils.BinaryUtil;
import com.quartet.utils.DateUtil;
import com.quartet.utils.FormatUtil;
import com.quartet.utils.LocaleUtils;
import com.quartet.utils.constant.MapServerConstant;
import com.quartet.utils.enums.AlarmTypeEnum;
import com.quartet.utils.enums.PlatformStatisticsEnum;
import com.quartet.utils.enums.TerminalOnLineEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.text.DecimalFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 终端位置表(TVehiclePositionInfo)表服务实现类
 *
 * @author makejava
 * @since 2021-05-09 12:32:16
 */
@Service("tTerminalPositionInfoService")
@Slf4j
public class TTerminalPositionInfoServiceImpl extends ServiceImpl<TTerminalPositionInfoDao, TTerminalPositionInfo> implements TTerminalPositionInfoService {

    @Autowired
    private TVehicleInfoDao tVehicleInfoDao;
    @Autowired
    private TCustomerInfoDao tCustomerInfoDao;
    @Autowired
    private TTerminalStockDao tTerminalStockDao;
    @Autowired
    private TOrderService tOrderService;
    @Autowired
    private TTerminalPositionInfoDao tTerminalPositionInfoDao;

    /**
     * 获取车辆位置信息信息
     *
     * @param tTerminalPositionInfoRequestDto
     * @return
     */
    @Override
    public PageResult<TTerminalPositionInfoResponseDto> selectTerminalPositionPage(TTerminalPositionInfoRequestDto tTerminalPositionInfoRequestDto) {
        PageResult<TTerminalPositionInfoResponseDto> pageResult = new PageResult<>();
        if (CollectionUtils.isEmpty(tTerminalPositionInfoRequestDto.getTerminalCodeList())) {
            pageResult.setTotal(0L);
            pageResult.setData(Collections.emptyList());
            return pageResult;
        }

        Page p = PageHelper.startPage(tTerminalPositionInfoRequestDto.getCurrent(), tTerminalPositionInfoRequestDto.getLimit());
        List<TTerminalPositionInfoResponseDto> tTerminalPositionInfoResponseDtoList = this.baseMapper.selectTerminalPositionPage(tTerminalPositionInfoRequestDto);
        setCurrentDayMileage(tTerminalPositionInfoResponseDtoList);
        pageResult.setData(tTerminalPositionInfoResponseDtoList);
        pageResult.setTotal(p.getTotal());
        return pageResult;
//        QueryWrapper<TVehiclePositionInfo> queryWrapper = new QueryWrapper<>();
//        if (!ObjectUtils.isEmpty(tVehicleAlarmInfoRequestDto.getVehicleStatus())) {
//            queryWrapper.lambda().eq(TVehiclePositionInfo::getVehicleStatus, tVehicleAlarmInfoRequestDto.getVehicleStatus());
//        }
//        queryWrapper.orderByDesc("create_time");
//        List<TVehiclePositionInfo> tVehiclePositionInfoList = this.baseMapper.selectList(queryWrapper);
//        List<TVehiclePositionInfoResponseDto> tVehiclePositionInfoResponseDtoList = tVehiclePositionInfoList.stream().map(tVehiclePositionInfo -> {
//            TVehiclePositionInfoResponseDto tVehiclePositionInfoResponseDto = BeanUtil.copyProperties(tVehiclePositionInfo, TVehiclePositionInfoResponseDto.class);
//            QueryWrapper<TVehicleInfo> queryWrapper1 = new QueryWrapper<>();
//            queryWrapper1.lambda().eq(TVehicleInfo::getEquipmentCode, tVehiclePositionInfo.getEquipmentCode());
//            TVehicleInfo tVehicleInfo = tVehicleInfoDao.selectOne(queryWrapper1);
//            if (ObjectUtils.isEmpty(tVehicleInfo)) {
//                return tVehiclePositionInfoResponseDto;
//            }
//            tVehiclePositionInfoResponseDto.setCarNumber(tVehicleInfo.getCarNumber());
//            tVehiclePositionInfoResponseDto.setEquipmentCode(tVehicleInfo.getEquipmentCode());
//            tVehiclePositionInfoResponseDto.setFlowCardNumber(tVehicleInfo.getFlowCardNumber());
//
//            QueryWrapper<TCustomerInfo> queryWrapper4 = new QueryWrapper<>();
//            queryWrapper4.lambda().eq(TCustomerInfo::getCustomerCode, tVehicleInfo.getCustomerCode());
//            TCustomerInfo tCustomerInfo = tCustomerInfoDao.selectOne(queryWrapper4);
//            if (ObjectUtils.isEmpty(tCustomerInfo)) {
//                return tVehiclePositionInfoResponseDto;
//            }
//            tVehiclePositionInfoResponseDto.setCustomerName(tCustomerInfo.getCustomerName());
//            tVehiclePositionInfoResponseDto.setCustomerCode(tCustomerInfo.getCustomerCode());
//            return tVehiclePositionInfoResponseDto;
//        }).filter(tVehiclePositionInfoResponseDto -> {
//                    if (CollectionUtils.isEmpty(tVehicleAlarmInfoRequestDto.getCustomerCodeList())) {
//                        return true;
//                    } else {
//                        return tVehicleAlarmInfoRequestDto.getCustomerCodeList().contains(tVehiclePositionInfoResponseDto.getCustomerCode());
//                    }
//                }
//        ).filter(tVehiclePositionInfoResponseDto -> {
//            if (StringUtils.isNotBlank(tVehicleAlarmInfoRequestDto.getQueryType()) && (StringUtils.isNotBlank(tVehicleAlarmInfoRequestDto.getQueryValue()))) {
//                return ReflectUtil.getFieldValue(tVehiclePositionInfoResponseDto, RandomUtils.getField(tVehicleAlarmInfoRequestDto.getQueryType())).toString().equals(tVehicleAlarmInfoRequestDto.getQueryValue());
//            } else {
//                return true;
//            }
//        }).collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(TVehiclePositionInfoResponseDto::getEquipmentCode))), ArrayList::new));
//        return tVehiclePositionInfoResponseDtoList;
    }

    /**
     * 查询终端轨迹信息
     *
     * @param tTerminalPositionInfoTrajectoryRequestDto
     * @return
     */
    @Override
    public PageResultMap<TTerminalPositionInfoResponseDto> selectTerminalPositionTrajectoryPage(TTerminalPositionInfoTrajectoryRequestDto tTerminalPositionInfoTrajectoryRequestDto) {
        Page p = PageHelper.startPage(tTerminalPositionInfoTrajectoryRequestDto.getCurrent(), tTerminalPositionInfoTrajectoryRequestDto.getLimit());
        List<TTerminalPositionInfoResponseDto> tTerminalPositionInfoResponseDtoList = this.baseMapper.selectTerminalPositionTrajectoryPage(tTerminalPositionInfoTrajectoryRequestDto);
        setCurrentDayMileage(tTerminalPositionInfoResponseDtoList);
        Map<String, List<TTerminalPositionInfoResponseDto>> map = tTerminalPositionInfoResponseDtoList.stream().collect(Collectors.groupingBy(TTerminalPositionInfoResponseDto::getTerminalCode));

        PageResultMap<TTerminalPositionInfoResponseDto> pageResult = new PageResultMap<>();
        pageResult.setData(map);
        pageResult.setTotal(p.getTotal());
        return pageResult;
    }

    /**
     * 计算当日里程并设置
     *
     * @param tTerminalPositionInfoResponseDtoList
     */
    private void setCurrentDayMileage(List<TTerminalPositionInfoResponseDto> tTerminalPositionInfoResponseDtoList) {
        tTerminalPositionInfoResponseDtoList.forEach(tTerminalPositionInfoResponseDto -> {
            //设置在线离线状态
            List<Integer> list = BinaryUtil.find1Cursor(tTerminalPositionInfoResponseDto.getStatus());
            if (list.contains(1)) {
                tTerminalPositionInfoResponseDto.setOnlineStatus(TerminalOnLineEnum.ON_LINE.getValue());
            } else {
                tTerminalPositionInfoResponseDto.setOnlineStatus(TerminalOnLineEnum.OFF_LINE.getValue());
            }
            //设置当日里程
            LocalDateTime createTime = tTerminalPositionInfoResponseDto.getCreateTime();
            LocalDateTime localDateTime = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0);
//            QueryWrapper<TTerminalPositionInfo> queryWrapper = new QueryWrapper<>();
//            queryWrapper.lambda().eq(TTerminalPositionInfo::getTerminalCode, tTerminalPositionInfoResponseDto.getTerminalCode())
//                    .le(TTerminalPositionInfo::getCreateTime, localDateTime).orderByDesc(TTerminalPositionInfo::getCreateTime).last(" limit 1");
            Float mileage  = this.baseMapper.selectCurrentMileage(tTerminalPositionInfoResponseDto.getTerminalCode(),localDateTime);
            if (ObjectUtils.isEmpty(mileage)) {
                tTerminalPositionInfoResponseDto.setCurrentDayMileage(0);
            } else {
                tTerminalPositionInfoResponseDto.setCurrentDayMileage(mileage/10);
            }
        });
    }

    /**
     * 查询终端位置轨迹坐标信息
     *
     * @param tTerminalPositionInfoTrajectoryRequestDto
     * @return
     */
    @Override
    public Map<String, List<TTerminalPositionTrajectoryCoordinateResponseDto>> selectTerminalPositionTrajectoryCoordinate(TTerminalPositionInfoTrajectoryRequestDto tTerminalPositionInfoTrajectoryRequestDto) {
        List<TTerminalPositionTrajectoryCoordinateResponseDto> tTerminalPositionTrajectoryCoordinateResponseDtoList = this.baseMapper.selectTerminalPositionTrajectoryCoordinate(tTerminalPositionInfoTrajectoryRequestDto);
        Map<String, List<TTerminalPositionTrajectoryCoordinateResponseDto>> map = tTerminalPositionTrajectoryCoordinateResponseDtoList.stream().collect(Collectors.groupingBy(TTerminalPositionTrajectoryCoordinateResponseDto::getTerminalCode));
        return map;
    }

    /**
     * 查询当前终端的里程集合
     *
     * @param terminalCodeList
     * @return
     */
    @Override
    public float queryTotalMileage(List<String> terminalCodeList) {
        List<Float> mileageList = this.baseMapper.queryTotalMileage(terminalCodeList);
        Float result = 0F;
        for (Float s : mileageList) {
            result = result + s;
        }
        return result/10;
    }

    /**
     * 获取一直的总里程数和运行时长
     *
     * @param terminalCodeList
     * @return
     */
    @Override
    public TVehicleFunctionDto queryTerminalTimeAndMileage(List<String> terminalCodeList) {
        long start=System.currentTimeMillis();
        TVehicleFunctionDto tVehicleFunctionDto = new TVehicleFunctionDto();
        LinkedList<String> axis = new LinkedList<>();
        LocalDateTime localDateTime = LocalDateTime.now();
        //生成最近7天的横坐标
        for (int i = 6; i >= 0; i--) {
            String s = DateUtil.localDateTimeFormat(localDateTime.minusDays(i), "yyyy-MM-dd");
            axis.add(s);
        }
        LinkedList<Double> totalMileageList=new LinkedList<>();
        LinkedList<Double> totalTimeList=new LinkedList<>();
        //获取最近一周的车辆位置信息
        LocalDateTime currentTime = LocalDateTime.now();
        LocalDateTime startTime = currentTime.minusDays(6).withHour(0).withMinute(0).withSecond(0);
//        List<TTerminalPositionDto> tTerminalPositionDtoList = this.baseMapper.queryTerminalPosition(startTime, terminalCodeList);
//        for (String axi : axis) {
//            List<TTerminalPositionDto> tTerminalPositionDtoList1 = tTerminalPositionDtoList.stream().filter(tTerminalPositionDto -> DateUtil.localDateTimeFormat(tTerminalPositionDto.getCreateTime(), "yyyy-MM-dd").equals(axi)).collect(Collectors.toList());
//            Double mileage = tTerminalPositionDtoList1.stream().collect(Collectors.summingDouble(TTerminalPositionDto::getMileage));
//            long count = tTerminalPositionDtoList1.stream().filter(tTerminalPositionDto -> tTerminalPositionDto.getSpeed()>0).count();
//            double hour = count * 3 / 60 / 60;
//            totalMileageList.add(mileage);
//            totalTimeList.add(hour);
//        }

        List<TTerminalPositionDto> tTerminalPositionMileageDtoList = this.baseMapper.queryTerminalMileage(startTime, terminalCodeList);
        List<TTerminalPositionDto> tTerminalPositionDtoSpeedList = this.baseMapper.queryTerminalSpeed(startTime, terminalCodeList);
        for (String axi : axis) {
            Double mileage = tTerminalPositionMileageDtoList.stream().filter(tTerminalPositionDto -> DateUtil.localDateTimeFormat(tTerminalPositionDto.getCreateTime(), "yyyy-MM-dd").equals(axi)).findAny().map(x -> x.getMileage()).orElse(0D);
            totalMileageList.add(mileage/10);

            Double count = tTerminalPositionDtoSpeedList.stream().filter(tTerminalPositionDto -> DateUtil.localDateTimeFormat(tTerminalPositionDto.getCreateTime(), "yyyy-MM-dd").equals(axi)).findAny().map(x -> x.getCount()).orElse(0D);
            totalTimeList.add(Double.parseDouble(FormatUtil.formatDouble(count * 3 / 60 / 60)));
        }

        tVehicleFunctionDto.setAxisList(axis);
        tVehicleFunctionDto.setTotalMileageList(totalMileageList);
        tVehicleFunctionDto.setTotalTimeList(totalTimeList);
        log.info("queryTerminalTimeAndMileage time is：{}",System.currentTimeMillis()-start);
        return tVehicleFunctionDto;
    }

    /**
     * 功能描述:
     *
     * @param terminalCodeList
     * @return java.util.List<com.quartet.modules.platform.dto.TVehicleStatusTotalTimeDto>
     * @date 2021/6/24 11:09
     */
    @Override
    public TVehicleStatusTotalTimeDto queryVehicleStatusTotalTime(List<String> terminalCodeList) {
        long start=System.currentTimeMillis();
        LinkedList<String> axis = new LinkedList<>();
        //获取最近一周的车辆位置信息
        LocalDateTime currentTime = LocalDateTime.now();
        LocalDateTime startTime = currentTime.minusDays(6).withHour(0).withMinute(0).withSecond(0);
        //生成最近7天的横坐标
        for (int i = 6; i >= 0; i--) {
            String s = DateUtil.localDateTimeFormat(currentTime.minusDays(i), "yyyy-MM-dd");
            axis.add(s);
        }
//        List<TVehicleStatusTotalTimeDto> tVehicleStatusTotalTimeDtoList = new ArrayList<>();
        List<VehicleStatusCount> platformAlarmCountList=new ArrayList<>();
        TVehicleStatusTotalTimeDto tVehicleStatusTotalTimeDto=new TVehicleStatusTotalTimeDto();
        //车辆行驶状态
        List<TTerminalPositionDto> tTerminalPositionDtoListDriving = this.baseMapper.queryVehicleStatusTotalCountWhenTravel(startTime, terminalCodeList, BinaryUtil.convert2Binary(Lists.newArrayList(1)));
        //车辆停止状态
        List<TTerminalPositionDto> tTerminalPositionDtoListStops = this.baseMapper.queryVehicleStatusTotalCountWhenStop(startTime, terminalCodeList, BinaryUtil.convert2Binary(Lists.newArrayList(1)));
//        //车辆无信号(未定位)
//        List<TTerminalPositionDto> tTerminalPositionDtoListNoSignal = this.baseMapper.queryVehicleStatusTotalCountWhenZero(startTime, terminalCodeList, BinaryUtil.convert2Binary(Lists.newArrayList(2)));
        //车辆离线(ACC关)
        List<TTerminalPositionDto> tTerminalPositionDtoListOffLine = this.baseMapper.queryVehicleStatusTotalCountWhenZero(startTime, terminalCodeList, BinaryUtil.convert2Binary(Lists.newArrayList(1)));

        //车辆行驶状态
        getVehicleStatusTotalTimeDto(axis, platformAlarmCountList, tTerminalPositionDtoListDriving, PlatformStatisticsEnum.DRIVING.getValue());
        //车辆停止状态
        getVehicleStatusTotalTimeDto(axis, platformAlarmCountList, tTerminalPositionDtoListStops, PlatformStatisticsEnum.PARKING.getValue());
//        //车辆无信号
//        getVehicleStatusTotalTimeDto(axis, tVehicleStatusTotalTimeDtoList, tTerminalPositionDtoListNoSignal, "无信号");
        //车辆无信号
        getVehicleStatusTotalTimeDto(axis, platformAlarmCountList, tTerminalPositionDtoListOffLine, PlatformStatisticsEnum.OFFLINE.getValue());

        tVehicleStatusTotalTimeDto.setXAxis(axis);
        tVehicleStatusTotalTimeDto.setPlatformAlarmCountList(platformAlarmCountList);
        log.info("queryVehicleStatusTotalTime time is：{}",System.currentTimeMillis()-start);
        return tVehicleStatusTotalTimeDto;
    }

    /**
     * 区域查终端
     *
     * @param tTerminalPositionInfoRegionLookupRequestDto
     * @return
     */
    @Override
    public List<TTerminalPositionInfoResponseDto> selectTerminalPositionWithRegion(TTerminalPositionInfoRegionLookupRequestDto tTerminalPositionInfoRegionLookupRequestDto) {
        return this.baseMapper.selectTerminalPositionWithRegion(tTerminalPositionInfoRegionLookupRequestDto);
    }

    /**
     * 历史区域查终端
     *
     * @param tTerminalPositionInfoRegionLookupRequestDto
     * @return
     */
    @Override
    public List<TTerminalPositionInfoResponseDto> selectTerminalPositionWithHistoryRegion(TTerminalPositionInfoRegionLookupRequestDto tTerminalPositionInfoRegionLookupRequestDto) {
        return this.baseMapper.selectTerminalPositionWithHistoryRegion(tTerminalPositionInfoRegionLookupRequestDto);
    }

    /**
     * 功能描述: 查询设备不同状态的个数
     *
     * @param
     * @return java.util.List<com.quartet.modules.platform.dto.TTerminalStatusNumber>
     * @author huipanxing huipanxing@chinasofti.com
     * @date 2021/6/29 9:49
     */
    @Override
    public List<TTerminalStatusNumber> queryTerminalStatusNum(List<String> tTerminalCodeList) {
        long start=System.currentTimeMillis();
        //在线个数
        int onLineCount = this.baseMapper.queryTerminalOnLineNum(tTerminalCodeList,BinaryUtil.convert2Binary(Lists.newArrayList(1)));
        //离线个数
        int offLineCount = this.baseMapper.queryTerminalOffLineNum(tTerminalCodeList,BinaryUtil.convert2Binary(Lists.newArrayList(1)));
        //报警个数
        int alarmCount = this.baseMapper.queryTerminalAlarmNum(tTerminalCodeList);
        List<TTerminalStatusNumber> tTerminalStatusNumberList = new ArrayList<>();
        TTerminalStatusNumber onLineBuilder = TTerminalStatusNumber.builder().terminalStatus(PlatformStatisticsEnum.ONLINE_DEVICES.getValue()).terminalNum(onLineCount).build();
        TTerminalStatusNumber offLineBuilder = TTerminalStatusNumber.builder().terminalStatus(PlatformStatisticsEnum.OFFLINE_EQUIPMENT.getValue()).terminalNum(offLineCount).build();
        TTerminalStatusNumber alarmBuilder = TTerminalStatusNumber.builder().terminalStatus(PlatformStatisticsEnum.ALARM_EQUIPMENT.getValue()).terminalNum(alarmCount).build();
        tTerminalStatusNumberList.add(onLineBuilder);
        tTerminalStatusNumberList.add(offLineBuilder);
        tTerminalStatusNumberList.add(alarmBuilder);
        log.info("queryTerminalStatusNum time is：{}",System.currentTimeMillis()-start);
        return tTerminalStatusNumberList;
    }

    /**
     * 功能描述: 获取车辆行驶里程的top10
     *
     * @param tTerminalInfoList
     * @return java.util.List<com.quartet.modules.platform.dto.TTerminalPositionDto>
     * @author huipanxing huipanxing@chinasofti.com
     * @date 2021/7/5 11:01
     */
    @Override
    public List<TTerminalPositionDto> queryTerminalMileageTop(List<String> tTerminalInfoList) {
        List<TTerminalPositionDto> tTerminalPositionDtoList = this.baseMapper.queryTerminalMileageTop(tTerminalInfoList);
        return tTerminalPositionDtoList;
    }

    /**
     * 功能描述: 车辆在线率
     *
     * @param
     * @param tTerminalInfoList
     * @return java.lang.String
     * @author huipanxing huipanxing@chinasofti.com
     * @date 2021/7/5 11:13
     */
    @Override
    public TerminalOnLineStatusResponseDto queryTerminalOnLineRate(List<String> tTerminalInfoList) {
        TerminalOnLineStatusResponseDto terminalOnLineStatusResponseDto = new TerminalOnLineStatusResponseDto();
        //当前总设备个数
        if (CollectionUtils.isEmpty(tTerminalInfoList)) {
            terminalOnLineStatusResponseDto.setOffLineTerminalCount(0);
            terminalOnLineStatusResponseDto.setOnLineTerminalCount(0);
            return terminalOnLineStatusResponseDto;
        }
        LocalDateTime startTime = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0);
        Integer totalSize = tTerminalInfoList.size();
        //当前在线设备个数
        int onLineSize = this.baseMapper.getOnlineTerminalCount(tTerminalInfoList, startTime);
        int offLineSize = tTerminalInfoList.size() - onLineSize;
        terminalOnLineStatusResponseDto.setOnLineTerminalCount(onLineSize);
        terminalOnLineStatusResponseDto.setOffLineTerminalCount(offLineSize);
        return terminalOnLineStatusResponseDto;
    }

    /**
     * 功能描述: 最近一周新增位置信息数据
     *
     * @param
     * @return java.util.Map<java.lang.String, java.lang.Integer>
     * @author huipanxing huipanxing@chinasofti.com
     * @date 2021/7/5 14:49
     */
    @Override
    public Map<String, Double> queryTerminalPositionLastWeek() {
        //获取最近一周的车辆位置信息
        DateTimeFormatter df = DateTimeFormatter.ofPattern("MM-dd");
        List<String> axis = new ArrayList<>();
        LocalDateTime currentTime = LocalDateTime.now();
        LocalDateTime startTime = currentTime.minusDays(6).withHour(0).withMinute(0).withSecond(0);
        for (int i = 6; i >= 0; i--) {
            String s = df.format(currentTime.minusDays(i));
            axis.add(s);
        }

        List<TTerminalPositionDto> tTerminalPositionDtoList = this.baseMapper.queryVehicleStatusTotalCountWhenOne(startTime, null, null);
        LinkedHashMap<String, Double> map = new LinkedHashMap<>();
        for (String axi : axis) {
            TTerminalPositionDto tTerminalPositionDto1 = tTerminalPositionDtoList.stream()
                    .filter(tTerminalPositionDto -> df.format(tTerminalPositionDto.getCreateTime()).equals(axi)).findAny().orElse(null);
            if (Objects.isNull(tTerminalPositionDto1)) {
                map.put(axi, 0D);
            } else {
                map.put(axi, tTerminalPositionDto1.getCount());
            }
        }
        return map;
    }


    /**
     * 功能描述: 最近一周新增报警信息数据
     *
     * @param
     * @return java.util.Map<java.time.LocalDateTime, java.lang.Double>
     * @author huipanxing huipanxing@chinasofti.com
     * @date 2021/7/5 15:07
     */
    @Override
    public Map<String, Double> queryTerminalAlarmLastWeek() {
        //获取最近一周的车辆位置信息
        DateTimeFormatter df = DateTimeFormatter.ofPattern("MM-dd");
        LocalDateTime currentTime = LocalDateTime.now();
        LocalDateTime startTime = currentTime.minusDays(6).withHour(0).withMinute(0).withSecond(0);
        List<TTerminalAlarmDto> tTerminalAlarmDtoList = this.baseMapper.queryTerminalAlarmData(startTime);
        Map<String, List<TTerminalAlarmDto>> dateTimeListMap = tTerminalAlarmDtoList.stream().collect(Collectors.groupingBy(TTerminalAlarmDto::getCreateTime));
//        Map<String, Double> map = new HashMap<>(7);

        //获取最近一周的车辆位置信息
        List<String> axis = new ArrayList<>();
        for (int i = 6; i >= 0; i--) {
            String s = df.format(currentTime.minusDays(i));
            axis.add(s);
        }
        LinkedHashMap<String, Double> map = new LinkedHashMap<>();
        axis.stream().forEach(s -> map.put(s, 0D));
        for (String localDateTime : dateTimeListMap.keySet()) {
            List<TTerminalAlarmDto> tTerminalAlarmDtoList1 = dateTimeListMap.get(localDateTime);
            double currentTotal = 0;
            for (TTerminalAlarmDto tTerminalAlarmDto : tTerminalAlarmDtoList1) {
                double count = tTerminalAlarmDto.getCount();
                String warningMark = tTerminalAlarmDto.getWarningMark();
                List<Integer> alarmType = JSON.parseArray(warningMark, Integer.class);
                currentTotal = currentTotal + count * alarmType.size();
            }
            map.put(localDateTime, currentTotal);
        }
        return map;
    }

    /**
     * 最近一周的报警总数
     *
     * @return
     */
    @Override
    public List<TPlatformAlarmTotalDto> getAlarmTotalCountLastWeek() {
        LocalDateTime currentTime = LocalDateTime.now();
        LocalDateTime startTime = currentTime.minusDays(6).withHour(0).withMinute(0).withSecond(0);
        List<Integer> alarmTypeList = MapServerConstant.alarmTypeList;
//        for (Integer integer : alarmTypeList) {
//            TPlatformAlarmTotalDto tPlatformAlarmTotalDto = new TPlatformAlarmTotalDto();
//            int alarmType = BinaryUtil.convert2Binary(Lists.newArrayList(Integer.parseInt(integer.toString())));
//            int count = this.baseMapper.getAlarmTotalCountLastWeek(startTime, alarmType);
//            tPlatformAlarmTotalDto.setCount(count);
//            if (LocaleUtils.getLocale().startsWith(MapServerConstant.EN)) {
//                tPlatformAlarmTotalDto.setAlarmTypeLabel(AlarmTypeEnum.find(integer.toString()).getDescriptionEn());
//            } else {
//                tPlatformAlarmTotalDto.setAlarmTypeLabel(AlarmTypeEnum.find(integer.toString()).getDescription());
//            }
//        }

        List<TPlatformAlarmTotalDto> tPlatformAlarmTotalDtoList = alarmTypeList.stream().map(integer -> {
            TPlatformAlarmTotalDto tPlatformAlarmTotalDto = new TPlatformAlarmTotalDto();
            String alarmType = String.valueOf(integer);
            int count = this.baseMapper.getAlarmTotalCountLastWeek(startTime, alarmType);
            tPlatformAlarmTotalDto.setCount(count);
            if (LocaleUtils.getLocale().startsWith(MapServerConstant.EN)) {
                tPlatformAlarmTotalDto.setAlarmTypeLabel(AlarmTypeEnum.find(integer.toString()).getDescriptionEn());
            } else {
                tPlatformAlarmTotalDto.setAlarmTypeLabel(AlarmTypeEnum.find(integer.toString()).getDescription());
            }
            return tPlatformAlarmTotalDto;
        }).collect(Collectors.toList());
        return tPlatformAlarmTotalDtoList;
    }

    /**
     *  查询终端实时位置
     * @param tTerminalCodeList
     * @return
     */
    @Override
    public List<TTerminalCurrentPositionResponseDto> queryTerminalCurrentPosition(List<String> tTerminalCodeList) {
        List<TTerminalCurrentPositionResponseDto> tTerminalCurrentPositionResponseDtoList = this.baseMapper.queryTerminalCurrentPosition(tTerminalCodeList);
        tTerminalCurrentPositionResponseDtoList.forEach(tTerminalCurrentPositionResponseDto -> {
            Integer status = tTerminalCurrentPositionResponseDto.getStatus();
            List<Integer> cursor = BinaryUtil.find1Cursor(status);
            if (cursor.contains(1)) {
                tTerminalCurrentPositionResponseDto.setOnline(true);
            } else {
                tTerminalCurrentPositionResponseDto.setOnline(false);
            }
        });
        return tTerminalCurrentPositionResponseDtoList;
    }

    /**
     * 功能描述: 获取车辆状态以及对象的时间现在统计
     *
     * @param axis
     * @param vehicleStatusCountList
     * @param tTerminalPositionDtoListDriving
     * @return void
     * @author huipanxing huipanxing@chinasofti.com
     * @date 2021/6/24 16:50
     */
    private void getVehicleStatusTotalTimeDto(List<String> axis, List<VehicleStatusCount> vehicleStatusCountList, List<TTerminalPositionDto> tTerminalPositionDtoListDriving, String status) {
        DecimalFormat df = new DecimalFormat("#.00");
        LinkedHashMap<String, Double> currentDayTotalTime1 = new LinkedHashMap<>(7);
        VehicleStatusCount vehicleStatusCount = new VehicleStatusCount();
        vehicleStatusCount.setVehicleStatus(status);
        for (String axi : axis) {
            List<TTerminalPositionDto> tTerminalPositionDtoList1 = tTerminalPositionDtoListDriving.stream().filter(tTerminalPositionDto -> DateUtil.localDateTimeFormat(tTerminalPositionDto.getCreateTime(), "yyyy-MM-dd").equals(axi)).collect(Collectors.toList());
            Double count = tTerminalPositionDtoList1.stream().collect(Collectors.summingDouble(TTerminalPositionDto::getCount));
            double hour = count * 3 / 60 / 60;
            currentDayTotalTime1.put(axi, Double.parseDouble(df.format(hour)));
        }
        vehicleStatusCount.setCountList(new ArrayList(currentDayTotalTime1.values()));
        vehicleStatusCountList.add(vehicleStatusCount);
    }
}
